﻿using UnityEngine;
using CustomGUI;
using System.Collections.Generic;
using System.IO;

public class GameplayScript : MonoBehaviour
{
	public GameObject pauseObject;
	public GameObject startArea;
	public GameObject loketFormulir;
	public GameObject loketPembayaran;
	public GameObject loketFoto;
	public GameObject loketPengambilan;
	public GUISkin skin;
	public Texture2D empptyBar;
	public Texture2D fullBar;
	//public GameObject npcObject;

	GameObject dataContainer;
	GameState gameState;
	bool mouseDownState;
	Transform selected;
	int layerMask;
	Vector3 lastPos;
	float gameTime = 150f;
	float xunit;
	float yunit;
	GUILabel pauseLabel;
	GUIButton exitButton;
	Vector2 pos;
	Vector2 size;
	int totalScore;
	public int totalNPC;

	readonly string sceneName = "Game";

	void Start ()
	{
		dataContainer = GameObject.Find("DataContainer");
		gameState = dataContainer.GetComponent<GameState>();
		gameState.CurrentScene = this.sceneName;
		pauseLabel = new GUILabel(40, 40, 20, 10, "PAUSE");
		pauseLabel.Visible = false;
		exitButton = new GUIButton(0, 40, 55, 20, 20, "Exit", GUICallback);
		exitButton.Visible = false;
		layerMask = ~(1 << 10);
		//startArea = this.transform.FindChild("StartArea").gameObject;
		//Instantiate(npcObject, this.startArea.transform.position, Quaternion.identity);
		xunit = Screen.width * 0.01f;
		yunit = Screen.height * 0.01f;
		pos = new Vector2(85*xunit, 5*yunit);
		size = new Vector2(13*xunit, 5*yunit);
		totalScore = 0;
		totalNPC = 0;
		//Debug.Log(gameState.score);
		//Debug.Log(((Dictionary<string, System.Object>)gameState.score).Count);
	}

	void OnGUI()
	{
		GUI.skin = skin;
		if(gameState.Paused)
			GUI.enabled = false;
		GUI.Label(new Rect(80*xunit, 2*yunit, 10*xunit, 10*yunit),"Time");
		GUI.Label(new Rect(80*xunit, 10*yunit, 30*xunit, 10*yunit),"Score:     " + totalScore);
		GUI.DrawTexture(new Rect(pos.x, pos.y, size.x, size.y), empptyBar);
		GUI.DrawTexture(new Rect(pos.x, pos.y, ((gameTime/150) * size.x), size.y), fullBar);
		GUI.enabled = true;
	}

	void GUICallback(int id, Dictionary<string, string> callbackRes)
	{
		/*if(gameState.End)
		{
			Debug.Log(dataContainer.GetComponent<GameState>().score);
			Dictionary<string, System.Object> temp = (Dictionary<string, System.Object>)gameState.score;
			int i;
			Debug.Log(temp.Count);
			for(i = 1; i <= 10; i++)
			{
				int num = temp[i.ToString()];
				if(num <= totalScore)
				{
					for(int x = 10; x > i; i--)
					{
						temp[x.ToString()] = temp[(x-1).ToString()];
					}
					temp[i.ToString()] = (System.Object)totalScore;
					gameState.score = temp;
					string filePath = Application.persistentDataPath + "\\data.json";
					var sr = File.CreateText(filePath);
					sr.WriteLine(MiniJSON.Json.Serialize(temp));
				}
			}
		}*/
		Application.LoadLevel("MainMenu");
	}

	void Update ()
	{
		if(gameTime > 0)
		{
			gameTime -= Time.deltaTime;
			if(gameTime <= 0)
			{
				gameTime = 0;
				startArea.GetComponent<StartAreaScripts>().spawn = false;
				gameState.End = true;
			}
		}
		if(gameState.End && totalNPC == 0)
		{
			pauseLabel.Text = "Score: " + totalScore;
			gameState.Paused = true;
			pauseLabel.Visible = true;
			exitButton.Visible = true;
			pauseObject.SetActive(true);
		}
		if(Input.GetKeyDown(KeyCode.Escape) && !gameState.End)
		{
			if(gameState.Paused)
			{
				gameState.Paused = false;
				Time.timeScale = 1;
				pauseLabel.Visible = false;
				exitButton.Visible = false;;
				pauseObject.SetActive(false);
			}
			else
			{
				gameState.Paused = true;
				Time.timeScale = 0;
				pauseLabel.Visible = true;
				exitButton.Visible = true;
				pauseObject.SetActive(true);
			}
		}

		if(Input.GetMouseButtonDown(0))
		{
			mouseDownState = true;
			selected = Raycast(Input.mousePosition);
			if(selected != null && selected.gameObject.GetComponent<NPCScript>().ProcedureState == NPCScript.FIN_STATE)
			{
				totalNPC -= 1;
				loketPengambilan.GetComponent<PengambilanScript>().RemoveNPC(selected.gameObject);
				totalScore += selected.gameObject.GetComponent<NPCScript>().Score;
				Destroy(selected.gameObject);
				selected = null;
			}
		}
		else if(Input.GetMouseButtonUp(0))
		{
			if(selected != null)
			{
				if(selected.gameObject.GetComponent<NPCScript>().objPosition != null &&
				   selected.gameObject.GetComponent<NPCScript>().objPosition.layer == 10)
				{
					if(selected.GetComponent<NPCScript>().ProcedureState == NPCScript.FORMULIR_STATE &&
					   selected.gameObject.GetComponent<NPCScript>().objPosition.CompareTag("Formulir"))
					{
						if(loketFormulir.GetComponent<FormulirScript>().NPCCount < 3)
						{
							startArea.GetComponent<StartAreaScripts>().RemoveNPC(selected.gameObject);
							loketFormulir.GetComponent<FormulirScript>().AddNPC(selected.gameObject);
							selected.parent = loketFormulir.transform;
						}
						else
						{
							selected.position = lastPos;
						}
					}
					else if(selected.GetComponent<NPCScript>().ProcedureState == NPCScript.BAYAR_STATE &&
					        selected.gameObject.GetComponent<NPCScript>().objPosition.CompareTag("Pembayaran"))
					{
						if(loketPembayaran.GetComponent<PembayaranScript>().NPCCount < 3)
						{
							loketFormulir.GetComponent<FormulirScript>().RemoveNPC(selected.gameObject);
							loketPembayaran.GetComponent<PembayaranScript>().AddNPC(selected.gameObject);
							selected.parent = loketPembayaran.transform;
						}
						else
						{
							selected.position = lastPos;
						}
					}
					else if(selected.GetComponent<NPCScript>().ProcedureState == NPCScript.FOTO_STATE &&
					        selected.gameObject.GetComponent<NPCScript>().objPosition.CompareTag("Foto"))
					{
						if(loketFoto.GetComponent<FotoScript>().NPCCount < 3)
						{
							loketPembayaran.GetComponent<PembayaranScript>().RemoveNPC(selected.gameObject);
							loketFoto.GetComponent<FotoScript>().AddNPC(selected.gameObject);
							selected.parent = loketFoto.transform;
						}
						else
						{
							selected.position = lastPos;
						}
					}
					else if(selected.GetComponent<NPCScript>().ProcedureState == NPCScript.PENGAMBILAN_STATE &&
					        selected.gameObject.GetComponent<NPCScript>().objPosition.CompareTag("Pengambilan"))
					{
						if(loketPengambilan.GetComponent<PengambilanScript>().NPCCount < 3)
						{
							loketFoto.GetComponent<FotoScript>().RemoveNPC(selected.gameObject);
							loketPengambilan.GetComponent<PengambilanScript>().AddNPC(selected.gameObject);
							selected.parent = loketPengambilan.transform;
						}
						else
						{
							selected.position = lastPos;
						}
					}
					else
						selected.position = lastPos;
				}
				else
				{
					selected.position = lastPos;
				}
				mouseDownState = false;
				selected = null;
			}
		}
		
		if(mouseDownState && selected != null)
			selected.position = ScreenToWorld(Input.mousePosition);

		/*Debug.Log("selected: " + selected);
		Debug.Log("MouseDownState: " + mouseDownState);
		if(selected != null)
			Debug.Log("Collide: " + selected.GetComponent<NPCScript>().objPosition);*/
		if(selected != null)
			Debug.Log(selected.GetComponent<NPCScript>().objPosition);
	}

	Vector3 ScreenToWorld(Vector2 pos)
	{
		Ray ray = Camera.main.ScreenPointToRay(pos);
		Vector3 vector = new Vector3(ray.origin.x, ray.origin.y, 5);
		return vector;
	}
	
	Transform Raycast(Vector2 pos)
	{
		Ray ray;
		RaycastHit hit = new RaycastHit();
		ray = Camera.main.ScreenPointToRay(pos);
		if(Physics.Raycast(ray, out hit, 100, layerMask) && 
		   hit.transform.gameObject.layer == 9)
		{
			lastPos = hit.transform.position;
			return hit.transform;
		}
		return null;
	}
}
